// pages/good/good.js
import {request} from "../../utils/request";
import config from "../../utils/config";

const app = getApp();
import {$wuxCountDown} from '../../lib/index'

Page({
    data: {
        good: [],
        good_id: null,
        picUrl: config.picUrl,
        custom: {},
        bannerIndex: 0,
        goodList:[],
        endHide:true,
        page:1,
        last_page:1,
        navBackground:'transparent',
        user:{},
        hideShadow:true,
        hideCart:true,
        hideBuy:true,
        cartNum:1,
        buyNum:1,
        remen:[],
        shouquan:[],
        selfYixiang:'',
        selfShouquan:'',
        allShouquan:0,
        allYixiang:0,
        soleType:'shouquan',
        home:false,
        hidePoster:true,
        poster:'',
        time:2525947,
        countdown:''
    },
    onLoad(options) {
        var op = wx.getLaunchOptionsSync()
        var pages = getCurrentPages(); // 获取页面栈
        var prevPage = pages[pages.length - 2]; // 上一个页面
        if(!prevPage && op.scene >= 1007){
            this.setData({home:true})
        }else{
            this.setData({home:false})
        }
        wx.showShareMenu({
            menus: ["shareAppMessage","shareTimeline"],
          })
        if('id' in options){
            this.setData({good_id:options.id})
        }else if('scene' in options){
            this.setData({good_id:options.scene})
        }
        var timeId = setInterval(()=>{
            var user = wx.getStorageSync('userInfo')
            if(user){
                this.setData({user})
                clearInterval(timeId)
            }
        },1500)
        this.setData({custom: wx.getMenuButtonBoundingClientRect()})
        this.getDetail()
        this.sendViewAdd()
        this.countdown()
    },
    countdown(){
        var runTime = this.data.time
        var year = Math.floor(runTime / 86400 / 365);
        runTime = runTime % (86400 * 365);
        var month = Math.floor(runTime / 86400 / 30);
        runTime = runTime % (86400 * 30);
        var day = Math.floor(runTime / 86400);
        runTime = runTime % 86400;
        var hour = Math.floor(runTime / 3600);
        runTime = runTime % 3600;
        var minute = Math.floor(runTime / 60);
        runTime = runTime % 60;
        var second = runTime;
        console.log(`${year}年${month}月${day}日${hour}时${minute}分${second}秒`)
        this.setData({time:this.data.time-1})
        setTimeout(this.countdown, 1000);
    },
    changeSole(e){
        this.setData({soleType:e.currentTarget.dataset.type})
    },
    /**
     * 获取当前商品详情
     */
    getDetail() {
        request({url: "/miniprogram/system/getGoodDetail", data: {id: this.data.good_id}, type: 'get'}).then(res => {
            if (res.code != 200) return false
            var collect = res.data.collect.map(item=>item.user_id)
            res.data.collect = collect
            res.data.banner.unshift({id:null,good_id:null,src:res.data.img})
            this.setData({good: res.data})
            this.getList()
            if(res.data.type < 3){
                this.getSole()
            }
            // 设置倒计时
            this.c1 = new $wuxCountDown({
                date: res.data.sales_date,
                render(date) {
                    // let years = this.leadingZeros(date.years, 0) + ' 年 '
                    let days = this.leadingZeros(date.days, 0) + ' 天 '
                    let hours = this.leadingZeros(date.hours, 0) + ' 时 '
                    let min = this.leadingZeros(date.min, 2) + ' 分 '
                    let sec = this.leadingZeros(date.sec, 2) + ' 秒 '
                    // if(years == '0 年') years = '';
                    if (days == '0 天 ') days = '';
                    if (days == '' && hours == '0 时 ') hours = '';
                    if (days == '' && hours == '' && min == '0 分 ') min = '';
                    this.setData({
                        c1: days + hours + min + sec,
                    })
                },
            })
        })
    },
    /**
     * banner切换事件
     */
    bannerChange(e) {
        this.setData({bannerIndex: e.detail.current})
    },
    kefu(){
        wx.openCustomerServiceChat({
            extInfo: {url: 'https://work.weixin.qq.com/kfid/kfcfc20feaa7f08dc21'},
            corpId: 'ww33b7dd5076024e7f',
        })
    },
    /**
     * 获取商品列表
     */
    getList() {
        // console.log(this.data)
        request({
            url:"/miniprogram/good/getSameGoodList",
            data:{
                sku:this.data.good.sku.map(item=>item.id),
                page:this.data.page,
                type:this.data.good.type,
                is_new:this.data.good.is_new
            },
            type:'post'
        }).then(res=>{
            if(res.code !== 0){
                wx.showToast({title:res.msg,icon:'none'})
                return false
            }
            if(this.data.page == 1){
                this.setData({goodList:[]})
            }
            this.setData({
                goodList:this.data.goodList.concat(res.data),
                last_page:res.last_page
            })
        })
    },
    /**
     * 关注发行商
     */
    guanzhu(e){
        var good = this.data.good
        request({url:"/miniprogram/system/brandConcern",data:{brand_id:this.data.good.brand_id.id,user_id:this.data.user.id,flag:e.currentTarget.dataset.flag},type:'post'}).then(res=>{
            if(res.code != 200){
                return false
            }
            good.brand_id.concern = res.data
            console.log(good)
            this.setData({good:good})
        })
    },
    /**
     * 收藏商品
     */
    shoucang(e){
        var good = this.data.good
        request({
            url:"/miniprogram/system/userCollect",
            data:{good_id:this.data.good.id,user_id:this.data.user.id,flag:e.currentTarget.dataset.flag},
            type:'post'
        }).then(res=>{
            if(res.code != 200){
                return false;
            }
            good.collect = res.data
            this.setData({good})
        })
    },
    /**
     * 关闭阴影层
     */
    toggleShadow(){this.setData({hideShadow:true,hideCart:true,hideBuy:true})},
    openCart(){
        if(this.data.good.is_new == 2 && this.data.good.sales_volume > 0){
            wx.showModal({
                title:"提示",
                content:"商品已经卖掉了，不可再次购买。",
                showCancel:false
            })
            return false
        }else if(this.data.user.authentication_type == 5){
            wx.showModal({
                title:"提示",
                content:"您未注册商户信息，无法购买商品",
                confirmText:"立即认证",
                success:res=>{
                    if(res.cancel) return false
                    wx.navigateTo({url:"/pages/merchant_auth/merchant_auth"})
                }
            })
            return false
        }else if(this.data.user.authentication_type == 4 && this.data.user.is_authentication != 2){
            wx.showModal({
                title:"提示",
                content:"您发起的商户审核还未通过，暂时不可购买，请等待审核通过后再进行购买操作。",
                showCancel:false
            })
            return false
        }else if(this.data.user.authentication_type == 3){
            wx.showModal({
                title:"提示",
                content:"您的身份是发行商，不可进行购买操作。",
                showCancel:false
            })
            return false
        }else if(this.data.good.type == 2 || this.data.good.type == 3){
            config.toast("城市限定或城市独家的剧本不可加入购物车",201,()=>{})
            return false
        }else if(this.data.user.authentication_type == 4 && this.data.user.is_authentication == 2){
            this.setData({hideCart:false,hideShadow:false})
        }
    },
    openBuy(){
        if(this.data.good.is_new == 2 && this.data.good.sales_volume > 0){
            //判断二手剧本已经卖掉了
            wx.showModal({
                title:"提示",
                content:"剧本已经卖掉了，不可再次购买。",
                showCancel:false
            })
            return false
        }else if(this.data.user.authentication_type == 5){
            //判断没有进行身份认证
            wx.showModal({
                title:"提示",
                content:"您未注册商户信息，无法购买商品",
                confirmText:"立即认证",
                success:res=>{
                    if(res.cancel) return false
                    wx.navigateTo({url:"/pages/shanghurenzheng/shanghurenzheng"})
                }
            })
            return false
        }else if(this.data.user.authentication_type == 4 && this.data.user.is_authentication != 2){
            //判断身份是否通过审核
            wx.showModal({
                title:"提示",
                content:"您发起的商户审核还未通过，暂时不可购买，请等待审核通过后再进行购买操作。",
                showCancel:false
            })
            return false
        }else if(this.data.user.authentication_type == 3){
            //判断发行商不可以购买剧本
            wx.showModal({
                title:"提示",
                content:"您的身份是发行商，不可进行购买操作。",
                showCancel:false
            })
            return false
        }else if(this.data.user.authentication_type == 4 && this.data.user.is_authentication == 2){
            if(this.data.good.type == 2 || this.data.good.type == 3){
                console.log(1)
                wx.navigateTo({url:"/pages/intention_collection/intention_collection?good_id="+this.data.good_id})
                //判断剧本是不是城市限定或者城市独家，是的话创建意向申请信息
            }else{
                //普通剧本打开数量购买面板，选择数量后进行剧本购买
                this.setData({hideBuy:false,hideShadow:false})
            }
        }

    },
    closeCart(){this.setData({hideCart:true,hideShadow:true})},
    closeBuy(){this.setData({hideBuy:true,hideShadow:true})},
    changeCartNum(e){
        if(this.data.good.is_new == 2){
            this.setData({cartNum:1})
        }else{
            this.setData({cartNum:e.detail.value})
        }
    },
    changeBuyNum(e){
        if(this.data.good.is_new == 2){
            this.setData({buyNum: 1})
        }else {
            this.setData({buyNum: e.detail.value})
        }
    },
    addNum(e){
        if(this.data.good.is_new == 2){
            this.setData({[e.currentTarget.dataset.type]:1})
        }else{
            var num = this.data[e.currentTarget.dataset.type]
            this.setData({[e.currentTarget.dataset.type]:num+1})
        }

    },
    subNum(e){
        if(this.data.good.is_new == 2){
            this.setData({[e.currentTarget.dataset.type]: 1})
        }else {
            var num = this.data[e.currentTarget.dataset.type]
            if (num > 1) {
                this.setData({[e.currentTarget.dataset.type]: num - 1})
            }
        }
    },
    /**
     * 下拉触底事件
     */
    onReachBottom() {
        if(this.data.page >= this.data.last_page){
            this.setData({endHide:false})
            return false
        }
        this.setData({page:this.data.page+1})
        this.getList()
    },
    /**
     * 设置分享事件
     */
    onShareAppMessage(res){
        return {
            title:this.data.good.name
        }
    },
    /**
     * 页面滚动事件
     */
    onPageScroll(e) {
        if(e.scrollTop > 505){
            this.setData({navBackground:'#fff'})
        }else{
            this.setData({navBackground:'transparent'})
        }
    },
    addCart(){
        var user = wx.getStorageSync('userInfo')
        request({
            url:"/miniprogram/order/addCart",
            data:{good_id:this.data.good.id, brand_id:this.data.good.brand_id.id, user_id:user.id, num:this.data.cartNum,type:1},
            type:'post'
        }).then(res=>{
            if(res.code == 200){
                wx.showToast({title:"添加成功"})
            }else{
                wx.showToast({title:res.msg,icon:'none'})
            }
            this.closeCart()
        })
    },
    buyGood(){
        var user = wx.getStorageSync('userInfo')
        request({
            url:"/miniprogram/order/addCart",
            data:{good_id:this.data.good.id, brand_id:this.data.good.brand_id.id, user_id:user.id, num:this.data.buyNum,type:2},
            type:'post'
        }).then(res=>{
            if(res.code == 201){
                wx.showToast({title:res.msg,icon:'none'})
                return false
            }
            this.closeCart()
            wx.navigateTo({
                url:`/pages/create_order/create_order?cart_id=`+res.data
            })
        })
    },
    getAddress(){
        wx.showLoading()
        wx.getFuzzyLocation({
            type:'wgs84',
            success:res=>{
                if(res.errno != 0){
                    wx.hideLoading()
                    wx.showToast({title:res.errMsg,icon:'none'})
                    return false
                }
                var getAddressUrl = "https://apis.map.qq.com/ws/geocoder/v1/?location=" + res.latitude + "," + res.longitude + "&key=LBJBZ-AMQ66-PHRSD-MXHZK-UFYW3-DZBYH";
                wx.request({
                    url:getAddressUrl,
                    success:rel=>{
                        wx.hideLoading()
                        rel = rel.data
                        request({
                            url:"/miniprogram/user/editDefaultAddress",
                            data:{province:rel.result.address_component.province,city:rel.result.address_component.city,county:rel.result.address_component.district,user_id:this.data.user.id},
                            type:'post'
                        }).then(res=>{
                            var user = wx.getStorageSync('userInfo')
                            user.province = rel.result.address_component.province
                            user.city = rel.result.address_component.city
                            user.county = rel.result.address_component.district
                            this.setData({user})
                            wx.setStorageSync('userInfo',user)
                            this.getDetail()
                        })
                    }
                })
            },
            fail(e) {
                console.log(e)
                wx.hideLoading()
            }
        })
    },
    sendViewAdd(){
        request({
            url:"/miniprogram/good/goodViewAdd",
            data:{good_id:this.data.good_id}
        }).then(res=>{

        })
    },
    getSole(){
        request({url:'/miniprogram/good/getGoodPageSole',data:{good_id:this.data.good_id,city:this.data.user.city}}).then(res=>{
            this.setData({
                yixiang:res.data.yixiang,
                shouquan:res.data.shouquan,
                selfYixiang:res.data.selfYixiang,
                selfShouquan:res.data.selfShouquan,
                allShouquan:res.data.allShouquan,
                allYixiang:res.data.allYixiang
            })
        })
    },
    toHome(){
        wx.switchTab({url:'/pages/index/index'})
    },
    create_poster(){
        var user = this.data.user

        if(!user.nickname || !user.avatar){
            config.toast("请先完善您的个人信息。",201,()=>{})
            return false;
        }
        wx.showLoading()
        request({
            url:"/miniprogram/order/createSharePic",
            data:{
                good_id:this.data.good_id,
                brand_id:this.data.good.brand_id.id,
                user_id:user.id,
            },
            type:'post'
        }).then(res=>{
            wx.hideLoading()
            if(res.code != 200){
                config.toast(res.msg,201,()=>{})
                return false
            }
            this.setData({
                hidePoster:false,
                poster:res.data,
            })
        })
    },
    closeShadow(){
        this.setData({hidePoster:true})
    },
    savePoster() {
        const that = this
        let fileName = new Date().valueOf();
        let filePath = wx.env.USER_DATA_PATH + '/' + fileName + '.jpg'
        wx.downloadFile({
            url: config.picUrl + this.data.poster,
            filePath: filePath,
            success: res => {
                wx.saveImageToPhotosAlbum({
                    filePath: filePath,
                    success(data) {
                        let fileMgr = wx.getFileSystemManager()
                        fileMgr.unlink({
                            filePath: filePath,
                            success() {
                                wx.showToast({
                                    title: '已保存至您的相册',
                                    icon: 'none',
                                    duration: 1500
                                });
                                that.setData({hidePoster: true, hideShadow: true})
                            }
                        })
                    },
                    fail(err) {
                        if (err.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || err.errMsg === "saveImageToPhotosAlbum:fail auth deny" || err.errMsg === "saveImageToPhotosAlbum:fail authorize no response") {
                            wx.showModal({
                                title: '提示',
                                content: '需要您授权保存相册',
                                showCancel: false,
                                success: modalSuccess => {
                                    wx.openSetting({
                                        success(settingdata) {
                                            if (settingdata.authSetting['scope.writePhotosAlbum']) {
                                                config.toast("获取权限成功，再次点击图片保存到相册的。", 201, () => {
                                                })
                                            } else {
                                                config.toast("获取权限失败，授权失败图片无法保存到本地相册", 201, () => {
                                                })
                                            }
                                        }
                                    })
                                }
                            })
                        }
                    }
                })
            }
        })
    },
})